package com.zhiyizhen.handheld.component.execute;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhiyizhen.handheld.R;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.RecyclerViewUtil;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.ToastUtil;
import com.zhiyizhen.handheld.common.constant.AppConstant;
import com.zhiyizhen.handheld.common.event.AddNewRecordEvent;
import com.zhiyizhen.handheld.common.view.BaseFragment;
import com.zhiyizhen.handheld.common.view.CommonDialog;
import com.zhiyizhen.handheld.component.execute.adapter.ExecuteRecordAdapter;
import com.zhiyizhen.handheld.component.execute.api.IExecuteService;
import com.zhiyizhen.handheld.component.execute.bean.ExecuteRecordBean;
import com.zhiyizhen.handheld.component.execute.bean.req.UpdateExecRecordReq;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.main.bean.ExecTypeBean;
import com.zhiyizhen.handheld.databinding.FragmentExecuteRecordBinding;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Locale;
import java.util.Map;

public class ExecuteRecordFragment extends BaseFragment {
    private FragmentExecuteRecordBinding binding;
    private ExecuteRecordAdapter adapter;
    private int mPage = 1;
    private LoginBean loginBean;
    private String orderId;
    private List<ExecTypeBean> execTypeBeanList;

    public static final int SHUYE = 1;
    public static final int LILIAO = 2;

    private int executeType = 1;

    public ExecuteRecordFragment(int executeType) {
        this.executeType = executeType;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentExecuteRecordBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loginBean = DataCache.getLoginBean();
        initView();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void setData(String orderId, List<ExecTypeBean> execTypeBeanList) {
        this.orderId = orderId;
        this.execTypeBeanList = execTypeBeanList;
        loadData(mPage);
        binding.emptyView.setVisibility(View.GONE);
        binding.recyclerView.setVisibility(View.VISIBLE);
    }

    public void setEmptyData() {
        binding.emptyView.setVisibility(View.VISIBLE);
        binding.recyclerView.setVisibility(View.GONE);
    }

    public void reloadData() {
        loadData(mPage);
    }

    private void initView() {
        RecyclerViewUtil.configLVRecyclerView(getContext(), binding.recyclerView);
        adapter = new ExecuteRecordAdapter(this.getContext());
        adapter.setExecTypeBeanList(execTypeBeanList);
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(1);
            }

            @Override
            public void onLoadMore() {
                loadData(mPage + 1);
            }
        });

        adapter.setOnEditClickListener(this::showAddExecuteDialog);
    }

    private CommonDialog dialog;
    public void showAddExecuteDialog(ExecuteRecordBean data) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_execute, (ViewGroup) getActivity().getWindow().getDecorView(), false);
        final TextView executeTimesTv = view.findViewById(R.id.executeTimesTv);
        final TextView executeNameTv = view.findViewById(R.id.executeNameTv);
        final EditText executeResultEdit = view.findViewById(R.id.executeResultEdit);
        final TextView executeTimeTv = view.findViewById(R.id.executeTimeTv);

        executeTimesTv.setText(String.format(Locale.getDefault(), "本次为第 %1$s 次执行。", data.getExecTimes()));
        executeNameTv.setText(String.format("执行人：%1$s", loginBean.getEmpName()));
        executeTimeTv.setText(String.format("执行时间：%1$s", data.getExecTime()));
        CommonDialog.Builder builder = new CommonDialog.Builder(getActivity());
        executeResultEdit.setText(data.getExecResult());
        builder.setView(view);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_button).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.okBtn).setOnClickListener(v -> {
            String executeResult = executeResultEdit.getText().toString().trim();
            if (TextUtils.isEmpty(executeResult)) {
                ToastUtil.showShort("请输入执行效果");
                return;
            }
            updateExecRecord(data.getRecordId(), executeResultEdit.getText().toString().trim());
        });
    }

    private void updateExecRecord(Integer recordId, String execResult) {
        UpdateExecRecordReq req = new UpdateExecRecordReq();
        req.setRecordId(recordId);
        req.setExecResult(execResult);
        ServiceFactory.getService(IExecuteService.class)
                .updateExecRecord(loginBean.getToken(), loginBean.getClinicId(), req)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        ToastUtil.showShort("操作成功");
                        dialog.dismiss();
                        if (executeType == SHUYE) {
                            EventBus.getDefault().post(new AddNewRecordEvent(AddNewRecordEvent.EXECUTE_RECORD_SHUYE));
                        } else {
                            EventBus.getDefault().post(new AddNewRecordEvent(AddNewRecordEvent.EXECUTE_RECORD_LILIAO));
                        }
                    }
                });
    }

    private void loadData(final int page) {
        Map<String, Object> map = new ArrayMap<>();
        map.put(AppConstant.PAGE_NO, page);
        map.put(AppConstant.PAGE_SIZE, AppConstant.PER_PAGE);

        ServiceFactory.getService(IExecuteService.class)
                .getRecordList(loginBean.getToken(), loginBean.getClinicId(), orderId, page, AppConstant.PER_PAGE)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    boolean hasMore = true;
                    boolean success = false;

                    @Override
                    protected void onSuccess(ResponseData<List<ExecuteRecordBean>> responseData) {
                        success = true;
                        mPage = page;

                        List<ExecuteRecordBean> list = responseData.getData();
                        if (mPage == 1) {
                            adapter.setData(list);
                        } else {
                            adapter.addAll(list);
                        }
                        adapter.setExecTypeBeanList(execTypeBeanList);
                        hasMore = (list != null && list.size() == AppConstant.PER_PAGE);
                    }

                    @Override
                    protected void onFinally() {
                        RecyclerViewUtil.loadComplete(binding.recyclerView, mPage, success, !hasMore, adapter.getItemCount() <= 0);
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void addNewRecord(AddNewRecordEvent event) {
        if ((event.getRecordType() == AddNewRecordEvent.EXECUTE_RECORD_SHUYE && executeType == SHUYE)
                || (event.getRecordType() == AddNewRecordEvent.EXECUTE_RECORD_LILIAO && executeType == LILIAO)) {
            if (!TextUtils.isEmpty(orderId)) {
                reloadData();
            }
        }
    }
}
